using System;
using CCWP7.STA;
using CCWP7.Model;
using Caliburn.Micro;
using Microsoft.Phone.Shell;
using Caliburn.Micro.Logging;
using System.Collections.Generic;
using CCWP7.CaliburnMicro.ViewModels;
using CCWP7.CaliburnMicro.Services;
using System.Windows;

namespace CCWP7.CaliburnMicro
{
    public class AppBootstrapper : PhoneBootstrapper
    {
        PhoneContainer container;
        IServerDataManager _serverDataManager;

        static AppBootstrapper()
        {
            LogManager.GetLog = type => new DebugLog(type);
        }

        protected override void Configure()
        {
            container = new PhoneContainer(RootFrame);

            container.PerRequest<MainPageViewModel>();
            container.PerRequest<AddServerPageViewModel>();
            container.PerRequest<ProjectsViewModel>();
            container.PerRequest<ProjectPageViewModel>();
            container.PerRequest<ServerPageViewModel>();
            container.PerRequest<AboutPageViewModel>();
            container.PerRequest<ServersViewModel>();
            container.PerRequest<IProductVersion, ProductVersion>();
            container.PerRequest<ServerProjectsViewModel>();
            container.PerRequest<ReadServer>();
            container.PerRequest<RefreshServer>();
            container.PerRequest<BrowserPageViewModel>();
            container.PerRequest<SettingsPageViewModel>();
            container.PerRequest<IShellTileDataService, ShellTileDataService>();
            container.RegisterWithAppSettings(typeof(Settings), "Settings", typeof(Settings));

            _serverDataManager = new ServerDataManager();
            container.Instance<IServerDataManager>(_serverDataManager);

            container.RegisterPhoneServices();

            //AddCustomConventions();
        }

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            base.OnStartup(sender, e);

            try
            {
                var ac = new AgentController();

                ac.RegisterAgent();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Could not register agent", MessageBoxButton.OK);
            }
        }

        protected override object GetInstance(Type service, string key)
        {
            return container.GetInstance(service, key);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }

        //static void AddCustomConventions()
        //{
        //    ConventionManager.AddElementConvention<Pivot>(Pivot.ItemsSourceProperty, "SelectedItem", "SelectionChanged").ApplyBinding =
        //        (viewModelType, path, property, element, convention) =>
        //        {
        //            ConventionManager
        //                .GetElementConvention(typeof(ItemsControl))
        //                .ApplyBinding(viewModelType, path, property, element, convention);
        //            ConventionManager
        //                .ConfigureSelectedItem(element, Pivot.SelectedItemProperty, viewModelType, path);
        //            ConventionManager
        //                .ApplyHeaderTemplate(element, Pivot.HeaderTemplateProperty, viewModelType);
        //        };

        //    ConventionManager.AddElementConvention<Panorama>(Panorama.ItemsSourceProperty, "SelectedItem", "SelectionChanged").ApplyBinding =
        //        (viewModelType, path, property, element, convention) =>
        //        {
        //            ConventionManager
        //                .GetElementConvention(typeof(ItemsControl))
        //                .ApplyBinding(viewModelType, path, property, element, convention);
        //            ConventionManager
        //                .ConfigureSelectedItem(element, Panorama.SelectedItemProperty, viewModelType, path);
        //            ConventionManager
        //                .ApplyHeaderTemplate(element, Panorama.HeaderTemplateProperty, viewModelType);
        //        };
        //}

        protected override void OnLaunch(object sender, LaunchingEventArgs e)
        {
            _serverDataManager.Load();

            base.OnLaunch(sender, e);
        }

        protected override void OnActivate(object sender, ActivatedEventArgs e)
        {
            if (_error != null)
                throw _error;

            base.OnActivate(sender, e);

            _serverDataManager.Load(PhoneApplicationService.Current.State);
        }

        protected override void OnDeactivate(object sender, DeactivatedEventArgs e)
        {
            _serverDataManager.Save(PhoneApplicationService.Current.State);

            base.OnDeactivate(sender, e);
        }

        protected override void OnExit(object sender, EventArgs e)
        {
            _serverDataManager.Save();

            base.OnExit(sender, e);
        }

        Exception _error;
        protected override void OnUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (_error == null)
            {
                var result = MessageBox.Show("Press OK to send us the error report", "Error has occurred", MessageBoxButton.OKCancel);

                if (result == MessageBoxResult.OK)
                {
                    new Microsoft.Phone.Tasks.EmailComposeTask() { To = "nzbee@live.com",
                    Subject = "CCWP7 error",
                    Body = e.ExceptionObject.ToString() }.Show();

                    _error = e.ExceptionObject;

                    e.Handled = true;
                }
            }

            base.OnUnhandledException(sender, e);
        }
    }
}
